# -*- coding: utf-8 -*-
"""
@author: wyb
@date: 2023/12/5
@time: 21:04
@desc: wdhwyb@hotmail.com
"""

import imaplib
import email
from email.header import decode_header

# 邮箱登录信息
email_address = "wdhwyb@hotmail.com"
password = "kdmicdbrsbquwpql"

# 连接邮箱服务器
# outlook.office365.com
mail = imaplib.IMAP4_SSL("outlook.office365.com")  # 请根据你的邮箱提供商修改主机名
mail.login(email_address, password)

# 选择邮箱中的收件箱
mail.select("inbox")

# 定义搜索条件，获取自2023-11-01后的邮件
search_criteria = '(FROM "49402612@qq.com" SINCE "10-Nov-2023")'
status, messages = mail.search(None, search_criteria)

# 获取最新一封邮件的ID
latest_email_id = messages[0].split()[-1]

# 获取邮件内容
status, msg_data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = msg_data[0][1]

# 解析邮件内容
email_message = email.message_from_bytes(raw_email)
subject, encoding = decode_header(email_message["Subject"])[0]
if isinstance(subject, bytes):
    subject = subject.decode(encoding if encoding else "utf-8")

# 打印邮件主题
print("Subject:", subject)

# 获取邮件正文
if email_message.is_multipart():
    for part in email_message.walk():
        if part.get_content_type() == "text/plain":
            body = part.get_payload(decode=True)
            print("Body:", body.decode("utf-8"))
else:
    body = email_message.get_payload(decode=True)
    print("Body:", body.decode("utf-8"))

# 关闭邮箱连接
mail.logout()

